import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';

// GET /api/sites/[id] - 获取工地详情
export async function GET(request: NextRequest) {
  const id = request.nextUrl.pathname.split('/').pop();
  if (!id) {
    return NextResponse.json(
      { error: '无效的ID' },
      { status: 400 }
    );
  }

  try {
    const site = await prisma.site.findUnique({
      where: { id },
      include: {
        expenses: {
          orderBy: {
            paymentDate: 'desc'
          }
        }
      }
    });

    if (!site) {
      return NextResponse.json(
        { error: '工地不存在' },
        { status: 404 }
      );
    }

    return NextResponse.json(site);
  } catch (error) {
    console.error('获取工地详情失败:', error);
    return NextResponse.json(
      { error: '获取工地详情失败' },
      { status: 500 }
    );
  }
}

// PUT /api/sites/[id] - 更新工地
export async function PUT(request: NextRequest) {
  const id = request.nextUrl.pathname.split('/').pop();
  if (!id) {
    return NextResponse.json(
      { error: '无效的ID' },
      { status: 400 }
    );
  }

  try {
    const data = await request.json();
    const site = await prisma.site.update({
      where: { id },
      data
    });

    return NextResponse.json(site);
  } catch (error) {
    console.error('更新工地失败:', error);
    if (error instanceof Error && error.message.includes('Record to update not found')) {
      return NextResponse.json(
        { error: '工地不存在' },
        { status: 404 }
      );
    }
    return NextResponse.json(
      { error: '更新工地失败' },
      { status: 500 }
    );
  }
}

// DELETE /api/sites/[id] - 删除工地
export async function DELETE(request: NextRequest) {
  const id = request.nextUrl.pathname.split('/').pop();
  if (!id) {
    return NextResponse.json(
      { error: '无效的ID' },
      { status: 400 }
    );
  }

  try {
    const site = await prisma.site.delete({
      where: { id }
    });

    return NextResponse.json(site);
  } catch (error) {
    console.error('删除工地失败:', error);
    if (error instanceof Error && error.message.includes('Record to delete does not exist')) {
      return NextResponse.json(
        { error: '工地不存在' },
        { status: 404 }
      );
    }
    return NextResponse.json(
      { error: '删除工地失败' },
      { status: 500 }
    );
  }
} 